# coding=utf-8
# 全世界最帅的帅哥
from flask import jsonify
from flask import request
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required, create_refresh_token, decode_token
from sqlalchemy.exc import OperationalError, SQLAlchemyError

from ysgg1_club_auth.auth_views.register_views import register_by_wx
from ysgg1_club_auth.comment.utils.jwt_manager import jwt_manager
from ysgg1_club_auth.constant.redis_prefix import RedisPrefix
from ysgg1_club_comment.modules.auth_user import AuthUser
from ysgg1_club_comment.redis_client import redis_client, jwt_redis_blocklist
from ysgg1_club_comment.utils.fbmsg import FBMsg


def login():
    try:
        request_data = request.get_json()
        code = str(request_data.get("code"))
        reminder_me = True if request_data.get("remind_me") else False
        login_key = RedisPrefix.LOGIN_PREFIX + code
        open_id = redis_client.get(login_key)
        if not open_id:
            return {"code": 200, "success": False, "message": "验证码错误, 请重试"}
        open_id = open_id.decode("utf-8")
        count = AuthUser.query.filter_by(user_name=open_id, is_delete=0).count()
        if not count:
            try:
                return_dict = register_by_wx(open_id)
                if return_dict["code"] == 200:
                    access_token = create_refresh_token(identity=open_id) if reminder_me else create_access_token(
                        identity=open_id)
                    return {"code": 200, "success": True, "token": access_token}
                return FBMsg.create_user_error_message()
            except (Exception, OperationalError, SQLAlchemyError):
                return FBMsg.create_user_error_message()

        # username = request.json.get("username", None)
        # password = request.json.get("password", None)
        # user = AuthUser.query.filter_by(user_name=username).first()
        # if not user:
        #     return FBMsg.login_error_message()
        # if not user.check_password(password):
        #     return FBMsg.login_error_message()

        access_token = create_refresh_token(identity=open_id) if reminder_me else create_access_token(
                        identity=open_id)
        return {"code": 200, "success": True, "token": access_token}
    except (Exception, OperationalError) as e:
        return FBMsg.login_error_message()


def logout():
    pass


@jwt_manager.token_in_blocklist_loader
def check_if_token_is_revoked(jwt_header, jwt_payload: dict):
    jti = jwt_payload["jti"]
    token_in_redis = jwt_redis_blocklist.get(jti)
    return token_in_redis is not None


@jwt_required()
def protected():
    # Access the identity of the current user with get_jwt_identity
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user), 200
